package com.ebelter.scaleblesdk.util;

import android.text.TextUtils;

import com.chipsea.healthscale.CsAlgoBuilderEx;
import com.ebelter.scaleblesdk.ble.model.FatResult;
import com.ebelter.scaleblesdk.common.BleFild;
import com.ebelter.scaleblesdk.model.MeasureResult;
import com.ebelter.scaleblesdk.model.OfflineMeasureResult;
import com.ebelter.scaleblesdk.model.ScaleUser;
import com.ebelter.scaleblesdk.model.WeightUnit;

/**
 * 测量结果分析器
 * Created by Sergio Pan on 2017/11/10.
 */

public class MeasureResultAnalyzer{
    private static final String TAG = "MeasureResultAnalyzer";
    private CsAlgoBuilderEx mBuilderEx = new CsAlgoBuilderEx();
    private static MeasureResultAnalyzer instance = new MeasureResultAnalyzer();

    private MeasureResultAnalyzer() {
    }

    public static MeasureResultAnalyzer getInstance() {
        return instance;
    }


    /**
     * 分析测量结果，得到分析结果
     * @param result
     * @param user
     * @return
     */
    public OfflineMeasureResult getOfflineMeasureResult(FatResult result, ScaleUser user) {
        if (result == null || user == null) {
            return null;
        }
        /*#################创建分析结果对象#################*/
        OfflineMeasureResult mResult = new OfflineMeasureResult();
        getResult(result, user, mResult);
        mResult.setSuspectedData(result.isSuspectedData());

        return mResult;
    }

    /**
     * 分析测量结果，得到分析结果
     */
    public MeasureResult getMeasureResult(FatResult result, ScaleUser user) {
        if (result == null || user == null) {
            return null;
        }
        MeasureResult mResult = new MeasureResult();
        getResult(result, user, mResult);
        return mResult;
    }

        /**
         * 分析测量结果，得到分析结果
         *
         * @param result
         * @param user
         * @return
         */
    private void getResult(FatResult result, ScaleUser user, MeasureResult mResult) {



        // 从测量结果中取出sdk计算基值
        final float weightResult = result.getWeight();
        final float fatResult = result.getFat();
        final float resistanceResult = result.getResistance();

        float resistanceResult2 = result.getResistance();


        if (TextUtils.equals(result.getConnectName(), BleFild.SCALE_NAME2)){
            ULog.i(TAG,"收到的阻抗="+resistanceResult2);
            //实测阻抗
            resistanceResult2= (float) ((resistanceResult*100+10000)/103-user.getHeight());
            ULog.i(TAG,"实测阻抗="+resistanceResult2);

            //加密阻抗
            resistanceResult2= (float) ((weightResult*40+resistanceResult2*60+10000)*1.0/100.0);
            ULog.i(TAG,"传入sdk的 加密阻抗="+resistanceResult2);
        }

        //  计算各种值
        //设置用户信息 身高，体重，性别 1-男 0-女，年龄，电阻
        int sex = user.getSex();
        int age = user.getAge();
        float height = user.getHeight();
        float target = user.getTarget();


        if (age < 18) {
            age = 18;
        } else if (age > 80) {
            age = 80;
        }
        int orSex = 1 - sex;

        try {
            // 设置sdk基值
            mBuilderEx.setUserInfo(height, weightResult
                    , (byte) orSex, age, resistanceResult2);
            ULog.i(TAG, "用户  分析测量结果 要计算的信息----身高--" + height
                    + "---体重--" + weightResult + "----脂肪---" + fatResult + "----阻抗---" + resistanceResult2 + "----目标体重---" + target +
                    "----性别----=" + sex + "---取反后的性别--=" + orSex);

            //设置用户角色，1为运动员，0为普通用户
            mBuilderEx.setMode(user.getRoleType());
        /*####################计算出各个指标值###############################*/
            float wr, bmr, vf, mv,muscleMass, bv, protein, bmi = 0;
            int ba, score;
            if (fatResult > 0.0f && age >= 18) {//脂肪率大于0则，计算各个指标
                wr = mBuilderEx.getTFR();
                bmr = mBuilderEx.getBMR();
                vf = mBuilderEx.getVFR();
                //骨骼肌
                mv = mBuilderEx.getSMM();
                muscleMass =mBuilderEx.getSLM();//肌肉量
                bv = mBuilderEx.getMSW();
                ba = (int) mBuilderEx.getBodyAge();
                protein = mBuilderEx.getPM();

                score = mBuilderEx.getScore();
                ULog.i(TAG, "----analyzeMeasureResult-----nike = " + user.getNike() + ", wr =" + wr + ", bmr =" + bmr + ", vf =" + vf + ", mv =" + mv + ", bv =" + bv
                        + ", fatResult = " + fatResult + ", weightResult = " + weightResult + ", ba = " + ba + ", protein = " + protein + ", score = " + score);
                // 蛋白质KG  转 百分比
                protein = dbzKgToPer(protein, weightResult);

                ULog.i(TAG, "-----analyzeMeasureResult------BMI-------" + bmi);

            } else {//脂肪率小于等于0，则各个指标无效
                wr = bmr = vf = mv = bv = protein =muscleMass= -1f;
                ba = score = 0;
            }

            //BMI
            bmi = getBmi(weightResult, height);

            //测量时间
            String year = result.getYear() + "";
            String month = numberFormat(result.getMonth() + "");
            String day = numberFormat(result.getDay() + "");
            String hour = numberFormat(result.getHour() + "");
            String minute = numberFormat(result.getMinute() + "");
            String sec = numberFormat(result.getSecond() + "");

            String measureTime = new StringBuffer(year).append("-").append(month)
                    .append("-").append(day).append(" ").append(hour).append(":")
                    .append(minute).append(":").append(sec).toString();


            // 设置基本信息
            mResult.setBtId(user.getBtId());
            mResult.setSex(user.getSex());
            mResult.setAge(user.getAge());
            mResult.setMac(user.getMac());
            mResult.setWeight(weightResult);
            mResult.setFat(fatResult);
            mResult.setMeasureTime(measureTime);
            //设置指标值
            mResult.setWaterRate(wr);
            mResult.setBmr(bmr);
            mResult.setVisceralFat(vf);
            mResult.setMuscleVolume(muscleMass);
            mResult.setBoneVolume(bv);
            mResult.setProtein(protein);
            mResult.setSkeletalMuscle(mv);
            mResult.setBmi(bmi);
            mResult.setResistance(resistanceResult);
            mResult.setBodyScore(score);
            mResult.setBpm(result.getBpm());
            mResult.setBodyAge(ba);
            mResult.setConnectBlueName(result.getConnectName());
            //默认单位为kg
            mResult.setWeightUnit(result.getUnitIsKG()?WeightUnit.KG.toString():WeightUnit.LB.toString());//zcq

            ULog.i(TAG,"最终发给展示的数据mResult----"+mResult.toString());
        }catch (Exception e){
            ULog.e(TAG, "-------getResult--------e.getMessage()= " +e.getMessage());
        }

    }

    private String numberFormat(String number) {
        return number.length() < 2 ? "0" + number : number;
    }

    private float getBmi(float weight, float userHeight) {
        float bmi = weight / (userHeight * userHeight / 10000);
        return  Math.round(bmi * 10)/ 10.0f;
    }

    private float dbzKgToPer(float dbz, float weight) {
        float preF = dbz / weight * 100;
        preF = Math.round(preF * 10) / 10.0f;
        preF = Math.min(preF, 100.0f);
        return preF;
    }

}
